package com.kkb.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author jack
 * @Version v1.0
 * @Description SqlSession工具类
 */
public class SqlSessionUtils {
    //定义私有静态的成员变量
    private static SqlSessionFactory sqlSessionFactory;

    //通过静态代码块 为静态的成员变量赋值
    static {
        try {
            //加载Mybatis的核心配置文件
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //构造SQLSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //构造方法私有
    private SqlSessionUtils(){}

    //提供公共方法, 返回SqlSession对象
    public static SqlSession openSession(){
        return sqlSessionFactory.openSession();
    }
}
